package com.ljx.rag.common.util;


import cn.hutool.core.util.RandomUtil;
import org.apache.commons.codec.digest.DigestUtils;

public class Sha256Util {

    /**
     * 随机盐值混合
     * 加密规则：SHA-256散列值每四个字符中间插入一个盐字符（方便后续解密）
     * @param str
     * @return
     */
    public static String encryptWithSalt(String str) {
        String salt = RandomUtil.randomString(16);
        String sha256Hex = DigestUtils.sha256Hex(str + salt);
        StringBuilder sb = new StringBuilder(80);
        for(int i = 0; i < 16; i++) {
            sb.append(sha256Hex.charAt(i * 4));
            sb.append(salt.charAt(i));
            sb.append(sha256Hex.charAt(i * 4 + 1));
            sb.append(sha256Hex.charAt(i * 4 + 2));
            sb.append(sha256Hex.charAt(i * 4 + 3));
        }
        return sb.toString();
    }

    public static boolean verifyIsSame(String str, String encryptStr) {
        StringBuilder sb1 = new StringBuilder(64); // 代表加密后的正确字符串
        StringBuilder sb2 = new StringBuilder(16); // 代表盐
        for(int i = 0; i < 16; i++) {
            sb1.append(encryptStr.charAt(i * 5));
            sb2.append(encryptStr.charAt(i * 5 + 1));
            sb1.append(encryptStr.charAt(i * 5 + 2));
            sb1.append(encryptStr.charAt(i * 5 + 3));
            sb1.append(encryptStr.charAt(i * 5 + 4));
        }
        return DigestUtils.sha256Hex(str + sb2).equals(sb1.toString());
    }


    public static void main(String[] args) {
        String encryptStr = encryptWithSalt("123456789");
        System.out.println(encryptStr);
        System.out.println(verifyIsSame("123456789", encryptStr));
        System.out.println(verifyIsSame("12345678910", encryptStr));
    }


}
